package org.example.dingtalkintegrationservice.dingtalk.user;
import com.alibaba.fastjson.JSON;
import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.OapiUserListsimpleRequest;
import com.dingtalk.api.request.OapiV2DepartmentListsubRequest;
import com.dingtalk.api.response.OapiUserListsimpleResponse;
import com.dingtalk.api.response.OapiV2DepartmentListsubResponse;
import groovy.json.JsonSlurper;
import org.example.dingtalkintegrationservice.exception.DingTalkCallExceptionGroovy;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;

import java.util.concurrent.TimeUnit;

@Component
class GetAllUserBaseInfo {
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    def getChildDeptIdList(parentId,access_token){
        DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/v2/department/listsub");
        OapiV2DepartmentListsubRequest req = new OapiV2DepartmentListsubRequest();
        req.setDeptId(parentId);
        req.setLanguage("zh_CN");
        OapiV2DepartmentListsubResponse rsp = client.execute(req, access_token);
        if (!rsp.success){
            throw new DingTalkCallExceptionGroovy(rsp.message)
        }
        def res =new JsonSlurper().parseText(rsp.getBody())

        def childDeptIdList=res.result.collect{it.dept_id}
//    println(parentId)
//    println(childDeptIdList)
        def subChildDeptIdList=[]
        childDeptIdList.forEach {subChildDeptIdList.addAll(getChildDeptIdList(it,access_token))}
//    println("A:"+childDeptIdList)
//    println("B:"+subChildDeptIdList)
        childDeptIdList.addAll(subChildDeptIdList)
        return childDeptIdList;
    }
    def getAllUserBaseInfo(access_token){
        def deptIdList=[1L]+getChildDeptIdList(1L,access_token)
        def userBaseInfoList=[]
        deptIdList.forEach {userBaseInfoList+=getUserBaseInfoBatch(it,access_token)}
        def userBaseInfoListDropDuplicate=userBaseInfoList.groupBy { it.userid }.values().collect { it[0] }
        JSON.toJSONString(userBaseInfoListDropDuplicate)
    }
    static def getUserBaseInfo(deptId, access_token){
        DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/user/listsimple");
        OapiUserListsimpleRequest req = new OapiUserListsimpleRequest();
        req.setDeptId(deptId);
        req.setCursor(0L);
        req.setSize(100L);
        req.setOrderField("custom");
        req.setContainAccessLimit(false);
        req.setLanguage("zh_CN");
        OapiUserListsimpleResponse rsp = client.execute(req, access_token)
        if (!rsp.success){
            throw new DingTalkCallExceptionGroovy(rsp.message)
        }
        JsonSlurper jsonSlurper=new JsonSlurper()
        def json=jsonSlurper.parseText(rsp.getBody())
        json["result"]
    }

    static def getUserBaseInfoBatch(deptId, access_token){
        def userInfoList=new ArrayList()
        def hasMore=true
        while (hasMore){
            def res=getUserBaseInfo(deptId,access_token)
            hasMore=res.containsKey("has_more")&&res["has_more"]=="true"
            userInfoList.addAll(res["list"])
        }
        userInfoList
    }
    String getAllUserBaseInfoFromRedis(access_token){
//        def jedis = new Jedis("localhost", 6379)
//        def value = jedis.get("dingUserBaseInfo")
        def value=redisTemplate.opsForValue().get("dingUserBaseInfo");
        if (value!=null){
            return value
        }
        else{
            def dingUserInfo=getAllUserBaseInfo(access_token)
//            jedis.setex("dingUserBaseInfo" ,70000,dingUserInfo)
            redisTemplate.opsForValue().set("dingUserBaseInfo", value,12, TimeUnit.HOURS);
            return dingUserInfo
        }
    }
    def exec(String token){
    return getAllUserBaseInfoFromRedis(token)
}
}
